package com.dragon.mmochat.model.scheduleJob.pkGame.activities;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.message.Mmochat_SendHonorChenHaoToOldServer;
import com.dragon.mmochat.message.Mmochat_SendMultiServerWuDaoResult;
import com.dragon.mmochat.model.MmochatTeam;
import com.dragon.mmochat.model.battle.MmochatBattle;
import com.dragon.mmochat.model.enumType.MmochatBattleType;
import com.dragon.mmochat.model.enumType.MmochatEventType;
import com.dragon.mmochat.model.enumType.MmochatRoleStateType;
import com.dragon.mmochat.model.enumType.MmochatTeamConditionType;
import com.dragon.mmochat.model.enumType.MmochatTeamStateType;
import com.dragon.mmochat.model.map.MmochatMap;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.service.MmochatBattleService;
import com.dragon.mmochat.service.MmochatChatService;
import com.dragon.mmochat.service.MmochatFriendService;
import com.dragon.mmochat.service.MmochatMainService;
import com.dragon.mmochat.service.MmochatMapService;
import com.dragon.mmochat.service.MmochatTeamService;
import com.dragon.mmochat.util.MmochatUtil;

//跨服武道会
public class MmochatMultiServerWuDaoPkGame implements MmochatPkGame {

	private static final int minPlayer = 2; // 开赛最少区服数要求
	public static int initScore = 90; // 武道会初始积分
	public static int maxScore = 90;// 最多多少积分

	private static Logger log = LoggerFactory
			.getLogger(MmochatWuDaoPkGame.class);
	private static ScheduledExecutorService pkThreadPool = Executors
			.newScheduledThreadPool(10);
	private static List<ScheduledFuture<?>> scheduleHandleList = new ArrayList<ScheduledFuture<?>>();
	public static Map<Integer, Boolean> wuDaoPkGameOverMap = new ConcurrentHashMap<Integer, Boolean>();
	public static Map<Integer, Boolean> wuDaoPkGameAwardMap = new ConcurrentHashMap<Integer, Boolean>();

	// mapId-->step；step:0-->3-->2-->1
	public static Map<Integer, Integer> wuDaoPkGameStepMap = new ConcurrentHashMap<Integer, Integer>();
	// 名次名单:mapId-->List
	public static Map<Integer, List<MmochatServerTeamInfo>> wuDaoPkGameWinTeamMap = new ConcurrentHashMap<Integer, List<MmochatServerTeamInfo>>();

	public static int startMapId = MmochatConstant.mapId_30级跨服武道会;
	public static int endMapId = MmochatConstant.mapId_MAX等级跨服武道会;

	// Map<mapId,<Inst,score>>:每个等级段每个区的总积分
	// public static Map<Integer, Map<Integer, Integer>> serverScores = new
	// ConcurrentHashMap<Integer, Map<Integer, Integer>>();

	@Override
	public void prepare() {
		try {
			int index = 0;
			for (int mapId = startMapId; mapId < endMapId; mapId++) {
				try {
					MmochatMap map = new MmochatMap();
					map.setMapId(mapId);
					// TODO:地图文件待定
					map.setMapDataId(MmochatConstant.mapDataId_跨服武道会);
					map.setCanChangeLine(false);
					map.setWalkToBattle(false);
					map.setCanFriendlyPk(false);
					map.setCanTransToFriend(false);
					map.setCanWatchPk(false);
					map.setTeamCondition(MmochatTeamConditionType.只允许同区服组队);
					map.setMapName("跨服武道");

					MmochatMapService.maps.put(map.getMapId(), map);
					index++;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			MmochatChatService.sendSystemMsgToAllServer("跨服武道大赛开始报名入场了，"
					+ "请大家到江宁找<武道会传送人>报名参加，报名成功后需要退出本区，" + "登陆<跨服专区>进场!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 每人3个积分, 系统随机匹配两队战斗,败者输1分,胜者平分败方所输积分.
	// 只剩一队时获取. 时间结束时存在多个队伍则积分最高的获胜.
	@Override
	public void start() {
		try {
			scheduleHandleList.clear();
			wuDaoPkGameOverMap.clear();
			wuDaoPkGameAwardMap.clear();
			wuDaoPkGameStepMap.clear();
			wuDaoPkGameWinTeamMap.clear();
			// serverScores.clear();
			for (int mapId = startMapId; mapId < endMapId; mapId++) {
				try {
					MmochatMap map = MmochatMapService.maps.get(mapId);
					if (map == null) {
						continue;
					}
					wuDaoPkGameOverMap.put(mapId, false);
					wuDaoPkGameStepMap.put(mapId, 0);
					wuDaoPkGameWinTeamMap.put(mapId,
							new ArrayList<MmochatServerTeamInfo>());
					Map<Integer, Integer> serverScore = new ConcurrentHashMap<Integer, Integer>();
					for (int line = 0; line < MmochatConstant.maxMapLineNum; line++) {
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							if (me != null) {
								serverScore.put(me.getRegServerInstId(), 0);
							}
						}
						if (serverScore.size() < minPlayer) {
							// 区服数不足,比赛结束
							for (MmochatPlayer me : map.getLineRoleMap(line)
									.values()) {
								kickOutFromWuDaoPkGame(me);
								MmochatChatService.sendSystemMsgToPerson(me,
										"您所在级别段的跨服武道会因参与区服数不足" + minPlayer
												+ "个区服,无法开赛!");
								log.debug(me.getName() + "因区服数不足离开武道会.");
							}
						} else {
							// 人数足够,设置每个玩家初始积分
							for (MmochatPlayer me : map.getLineRoleMap(line)
									.values()) {
								me.setCommonActivityScore(initScore);
								MmochatChatService.sendSystemMsgToPerson(me,
										"比赛即将开始，您的体力值为" + initScore
												+ "点，体力为0时无法继续比赛。");
							}

							// 开始比赛,每隔1分钟自动匹配队伍对战,直到只剩最后一名或一队
							ScheduledFuture<?> fightHandle = pkThreadPool
									.scheduleWithFixedDelay(
											new RandomTeamFight(map, line), 10,
											90, TimeUnit.SECONDS);
							scheduleHandleList.add(fightHandle);
						}
					}
					// serverScores.put(mapId, serverScore);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void end() {
		try {
			// 停止战斗线程
			closeFightThread();
			for (int mapId = startMapId; mapId < endMapId; mapId++) {
				try {
					MmochatMap map = MmochatMapService.maps.get(mapId);
					if (map == null) {
						continue;
					}

					// 改变状态
					if (wuDaoPkGameOverMap.get(map.getMapId()) != null
							&& !wuDaoPkGameOverMap.get(map.getMapId())) {
						synchronized (map) {
							if (!wuDaoPkGameOverMap.get(map.getMapId())) {
								wuDaoPkGameOverMap.put(map.getMapId(), true);
							} else {
								continue;
							}
						}
						// 发放奖励,剩下的玩家按积分最高的队伍获胜
						// dealAward(map);
					}

					// 将地图内的所有人转移到固定地图,并解散队伍
					for (int line = 0; line < MmochatConstant.maxMapLineNum; line++) {
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							kickOutFromWuDaoPkGame(me);
						}
					}
					MmochatMapService.maps.remove(map.getMapId());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// MmochatChatService.sendSystemMsg("本次武道会已圆满结束!");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 停止自动匹配战斗
	public static void closeFightThread() {
		try {
			for (ScheduledFuture<?> handle : scheduleHandleList) {
				try {
					handle.cancel(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			scheduleHandleList.clear();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 自动随机匹配战斗
	// 空闲的玩家未经系统操作不会变成战斗状态
	// 战斗状态的玩家可能在匹配过程中变成空闲状态
	class RandomTeamFight implements Runnable {
		private MmochatMap map;
		private int line;

		public RandomTeamFight(MmochatMap map, int line) {
			this.map = map;
			this.line = line;
		}

		@Override
		public void run() {
			try {
				// 检测比赛是否结束
				if (isWuDaoPkOver(map, line)) {
					return;
				}

				List<MmochatPlayer> freePlayerList = new ArrayList<MmochatPlayer>();
				// 掉线或离开地图的玩家会自动从地图玩家中去除
				for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
					if (!me.isInBattle() && me.getCommonActivityScore() <= 0) {
						// 积分不足，请出武道会
						kickOutFromWuDaoPkGame(me);
						MmochatChatService.sendSystemMsgToPerson(me,
								"您的武道会积分不足，被请离了会场。");
					}

					// 空闲的个人或队长
					if (me.getCommonActivityScore() > 0
							&& !me.isInBattle()
							&& MmochatTeamService.getTeamState(me) != MmochatTeamStateType.队员) {
						// 锁定状态,锁定后不能组队,不能加人,不能离图
						if (me.lockState(MmochatRoleStateType.准备进入武道会战斗)) { // ?何时unlock,不要漏了
							freePlayerList.add(me);
						}
					}
				}
				if (freePlayerList.size() > 1) {
					// 乱序排序
					Collections.shuffle(freePlayerList);

					int fightTeamNum = freePlayerList.size();

					// 可能其中一方在此时掉线或离开游戏,但仍将以自动战斗方式参加战斗
					// 如果战斗结束时发现此人不在此地图或离线,则判断其为弃权
					for (int i = 0; i < fightTeamNum - 1; i++) {
						MmochatPlayer person1 = freePlayerList.get(i);
						if (person1.isFreeState()) {
							// 已经进入战斗
							continue;
						}
						for (int j = i + 1; j < fightTeamNum; j++) {
							MmochatPlayer person2 = freePlayerList.get(j);
							if (person2.isFreeState()) {
								// 已经进入战斗
								continue;
							}
							if (person1.getRegServerInstId() == person2
									.getRegServerInstId()) {
								// 同一个服的
								continue;
							}
							// 第一队人
							List<MmochatPlayer> team1 = new ArrayList<MmochatPlayer>();
							if (person1.isInTeam()) {
								MmochatTeam team = MmochatTeamService.teams
										.get(person1.getTeamId());
								if (team == null) {
									person1.leaveTeam();
									team1.add(person1);
								} else {
									for (Integer roleId : team.getMemberId()
											.values()) {
										MmochatPlayer member = MmochatMainService
												.getRoleFromBuffer(roleId);
										if (member != null) {
											team1.add(member);
										}
									}
								}
							} else {
								team1.add(person1);
							}

							// 第二队人
							List<MmochatPlayer> team2 = new ArrayList<MmochatPlayer>();
							if (person2.isInTeam()) {
								MmochatTeam team = MmochatTeamService.teams
										.get(person2.getTeamId());
								if (team == null) {
									person2.leaveTeam();
									team2.add(person2);
								} else {
									for (Integer roleId : team.getMemberId()
											.values()) {
										MmochatPlayer member = MmochatMainService
												.getRoleFromBuffer(roleId);
										if (member != null) {
											team2.add(member);
										}
									}
								}
							} else {
								team2.add(person2);
							}

							if (team1.contains(person2)
									|| team2.contains(person1)) {
								// 同一队...应该不可能出现
								person1.unLockState();
								person2.unLockState();
								continue;
							}
							// 进入战斗
							person1.unLockState();
							person2.unLockState();
							MmochatBattle battle = MmochatBattleService
									.enterPVPBattle(map.getMapId(),
											(byte) line, team1, team2,
											MmochatBattleType.跨服武道会比赛);

							// 不允许逃跑
							if (battle != null) {
								battle.setCanEscape(false);
								// 600人算，共150队，75组战斗，共3秒
								try {
									Thread.sleep(50);
								} catch (Exception e) {
									e.printStackTrace();
								}
								break;
							}
						}
					}
				}
				for (MmochatPlayer me : freePlayerList) {
					if (me.getState() == MmochatRoleStateType.准备进入武道会战斗) {
						me.unLockState();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	// 武道会是否结束
	public static boolean isWuDaoPkOver(MmochatPlayer me) {
		if (me == null) {
			return true;
		}
		// TODO:与MmochatNpcService中的level_line_map要一致
		// level->line, 30,40,50,60,70,80,90,100,110,120
		int[] level_line_map = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		int teamIndex = me.getLevel() / 10 - 3;
		if (teamIndex < 0 || teamIndex >= level_line_map.length) {
			return true;
		}

		// 进入比武场
		int targetMapId = startMapId + teamIndex;
		MmochatMap map = MmochatMapService.getMapByMapId(targetMapId);
		if (map == null) {
			return true;
		}
		return isWuDaoPkOver(map, me.getLine());
	}

	// 将玩家请离武道会，请回原服务器
	public static void kickOutFromWuDaoPkGame(MmochatPlayer me) {
		// 停止战斗
		if (me.isInBattle()) {
			MmochatBattle battle = MmochatBattleService.battles.get(me
					.getBattleId());
			if (battle != null) {
				battle.closeBattle();
			}
		}
		// 积分清0
		me.setCommonActivityScore(0);
		// 离队
		if (me.isInTeam()) {
			MmochatTeam team = MmochatTeamService.teams.get(me.getTeamId());
			team.leaveTeam(me.getRoleId());
		}

		MmochatChatService.sendSystemMsgToPerson(me, "与跨服专区断开连接...请退出!");
		MmochatFriendService.sendMsgToPersonByFriendMessage(me,
				"您已结束比赛。与跨服专区断开连接...请退出返回原区服!");
		// 从本跨服服务器中清除
		MmochatMainService.leaveGame(me, false);
		log.debug("玩家" + me.getName() + "被送出跨服武道场");

	}

	// 武道会是否结束
	public static boolean isWuDaoPkOver(MmochatMap map, int line) {
		if (map == null || map.getLineRoleMap(line).size() == 0
				|| wuDaoPkGameOverMap.get(map.getMapId()) == null
				|| wuDaoPkGameOverMap.get(map.getMapId())) {
			return true;
		}

		// 检测剩几个区服的人
		Map<Integer, Integer> serverMap = new ConcurrentHashMap<Integer, Integer>();
		for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
			if (me.getCommonActivityScore() > 0) {
				serverMap.put(me.getRegServerInstId(), 0);
			}
		}

		synchronized (map) {
			// wuDaoPkGameStepMap
			Integer step = wuDaoPkGameStepMap.get(map.getMapId());
			if (step == null) {
				step = 0;
				wuDaoPkGameStepMap.put(map.getMapId(), step);
			}
			int curServerNum = serverMap.size();
			switch (step) {
			case 0: {
				// 未决出前三阶段
				if (curServerNum > 3) {
					// 当前区服多于3个，比赛未结束
					return false;
				} else if (curServerNum == 3) {
					// 当前区服数正好3个，则决出前三名
					step = 3;
					wuDaoPkGameStepMap.put(map.getMapId(), step);
					// 下发奖励:所有在场发2000威望和第三名称号，并公布消息，进入前三强区服
					dealStepAward(map, line, 2000, 3);
					return false;
				} else if (curServerNum == 2) {
					// 当前区服数正好2个，则决出前二名
					step = 2;
					wuDaoPkGameStepMap.put(map.getMapId(), step);
					// 下发奖励:所有在场发3000威望和第二名称号，并公布消息，进入前二强区服
					dealStepAward(map, line, 3000, 2);
					return false;
				} else if (curServerNum == 1) {
					// 当前区服数正好1个，则决出前一名
					step = 1;
					wuDaoPkGameStepMap.put(map.getMapId(), step);
					// 下发奖励:所有在场发5000威望和第一名称号，并公布消息，进入前一强区服
					dealStepAward(map, line, 5000, 1);
					// 将第一名名单保存数据库
					dealWinner(map, line);
					// 比赛结束
					if (wuDaoPkGameOverMap.get(map.getMapId()) != null
							&& !wuDaoPkGameOverMap.get(map.getMapId())) {
						wuDaoPkGameOverMap.put(map.getMapId(), true);

						// 将所有人清出场地
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							kickOutFromWuDaoPkGame(me);
						}
					}
					return true;
				} else if (curServerNum == 0) {
					// 比赛结束
					if (wuDaoPkGameOverMap.get(map.getMapId()) != null
							&& !wuDaoPkGameOverMap.get(map.getMapId())) {
						wuDaoPkGameOverMap.put(map.getMapId(), true);

						// 将所有人清出场地
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							kickOutFromWuDaoPkGame(me);
						}
					}
					return true;
				}
				break;
			}
			case 3: {
				// 已决出前三名阶段
				if (curServerNum == 2) {
					// 当前区服数正好2个，则决出前二名
					step = 2;
					wuDaoPkGameStepMap.put(map.getMapId(), step);
					// 下发奖励:所有在场发1000威望和第二名称号，并公布消息，进入前二强区服
					dealStepAward(map, line, 1000, 2);
					return false;
				} else if (curServerNum == 1) {
					// 当前区服数正好1个，则决出前一名
					step = 1;
					wuDaoPkGameStepMap.put(map.getMapId(), step);
					// 下发奖励:所有在场发3000威望和第一名称号，并公布消息，进入前一强区服
					dealStepAward(map, line, 3000, 1);
					// 将第一名名单保存数据库
					dealWinner(map, line);
					// 比赛结束
					if (wuDaoPkGameOverMap.get(map.getMapId()) != null
							&& !wuDaoPkGameOverMap.get(map.getMapId())) {
						wuDaoPkGameOverMap.put(map.getMapId(), true);

						// 将所有人清出场地
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							kickOutFromWuDaoPkGame(me);
						}
					}
					return true;
				} else if (curServerNum == 0) {
					// 比赛结束
					if (wuDaoPkGameOverMap.get(map.getMapId()) != null
							&& !wuDaoPkGameOverMap.get(map.getMapId())) {
						wuDaoPkGameOverMap.put(map.getMapId(), true);

						// 将所有人清出场地
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							kickOutFromWuDaoPkGame(me);
						}
					}
					return true;
				}
				break;
			}
			case 2: {
				// 已决出前二名阶段
				if (curServerNum == 1) {
					// 当前区服数正好1个，则决出前一名
					step = 1;
					wuDaoPkGameStepMap.put(map.getMapId(), step);
					// 下发奖励:所有在场发2000威望和第一名称号，并公布消息，进入前一强区服
					dealStepAward(map, line, 2000, 1);
					// 将第一名名单保存数据库
					dealWinner(map, line);
					// 比赛结束
					if (wuDaoPkGameOverMap.get(map.getMapId()) != null
							&& !wuDaoPkGameOverMap.get(map.getMapId())) {
						wuDaoPkGameOverMap.put(map.getMapId(), true);

						// 将所有人清出场地
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							kickOutFromWuDaoPkGame(me);
						}
					}
					return true;
				} else if (curServerNum == 0) {
					// 比赛结束
					if (wuDaoPkGameOverMap.get(map.getMapId()) != null
							&& !wuDaoPkGameOverMap.get(map.getMapId())) {
						wuDaoPkGameOverMap.put(map.getMapId(), true);

						// 将所有人清出场地
						for (MmochatPlayer me : map.getLineRoleMap(line)
								.values()) {
							kickOutFromWuDaoPkGame(me);
						}
					}
					return true;
				}
				break;
			}
			default: {
				// 比赛结束
				if (wuDaoPkGameOverMap.get(map.getMapId()) != null
						&& !wuDaoPkGameOverMap.get(map.getMapId())) {
					wuDaoPkGameOverMap.put(map.getMapId(), true);

					// 将所有人清出场地
					for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
						kickOutFromWuDaoPkGame(me);
					}
				}
				return true;
			}
			}
		}

		return false;
	}

	// 下发奖励:所有在场发3000威望和第三名称号，并公布消息，进入前三强区服
	// step=3:前3名、step=2:前2名；step=1:第一名；根据名次发放称号，系统消息
	// 所有场内玩家获得addHonor威望
	private static void dealStepAward(MmochatMap map, int line, int addHonor,
			int step) {
		Map<Integer, String> serverMap = new ConcurrentHashMap<Integer, String>();
		List<MmochatServerTeamInfo> serverTeam = wuDaoPkGameWinTeamMap.get(map
				.getMapId());
		for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
			if (me.getCommonActivityScore() > 0) {
				MmochatServerTeamInfo curTeam = null;
				for (MmochatServerTeamInfo team : serverTeam) {
					if (team.getServerInstId() == me.getRegServerInstId()) {
						curTeam = team;
						curTeam.clear();
						break;
					}
				}
				if (curTeam == null) {
					curTeam = new MmochatServerTeamInfo();
					curTeam.setServerInstId(me.getRegServerInstId());
					serverTeam.add(curTeam);
				}
				curTeam.setPrority(1000 * (4 - step));
				if (me.getCurChenHaoInfo() != null) {
					curTeam.setServerName(me.getCurChenHaoInfo());
				}
			}
		}
		for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
			if (me.getCommonActivityScore() > 0) {
				if (me.getCurChenHaoInfo() != null) {
					serverMap.put(me.getRegServerInstId(), me
							.getCurChenHaoInfo());
				}
				MmochatServerTeamInfo curTeam = null;
				for (MmochatServerTeamInfo team : serverTeam) {
					if (team.getServerInstId() == me.getRegServerInstId()) {
						curTeam = team;
						break;
					}
				}
				if (curTeam != null) {
					String content = me.getName()
							+ "(ID:"
							+ Integer
									.toHexString((me.getRoleId() % 10000000) * 3)
							+ ")\n";
					curTeam.addMemberInfo(content);
				}
				// 下发声望、称号奖励
				Mmochat_SendHonorChenHaoToOldServer pack = new Mmochat_SendHonorChenHaoToOldServer(
						me.getRegServerInstId());
				pack.setRoleId(me.getRoleId() % 10000000);
				pack.setAddHonor(addHonor);
				pack.setIndex(step - 1);
				MmochatUtil.sendMultiServerPack(pack);
			}
		}
		String msg = "";
		String serverName = "";
		for (String sName : serverMap.values()) {
			serverName += sName + "、";
		}
		int levelRange = (map.getMapId() - startMapId) * 10 + 30;
		if (step == 3) {
			msg = "恭喜以下区服晋级" + levelRange + "级别段跨服武道的前三强(排名不分先后):"
					+ MmochatUtil.wrapColor(serverName, Color.yellow)
					+ "比赛正在继续!";
		} else if (step == 2) {
			msg = "恭喜以下区服晋级" + levelRange + "级别段跨服武道的前二强(排名不分先后):"
					+ MmochatUtil.wrapColor(serverName, Color.yellow)
					+ "比赛正在继续!";
		} else if (step == 1) {
			msg = MmochatUtil.wrapColor(serverName, Color.red)
					+ MmochatUtil.wrapColor("力战群服，获得了" + levelRange
							+ "级别段跨服武道的冠军!", Color.yellow);
		}
		// 获胜消息发给所有区服及场内玩家
		MmochatChatService.sendSystemMsg(msg);
		MmochatChatService.sendSystemMsgToAllServer(msg);
	}

	// 将第一名区服玩家名单发给各区服
	private static void dealWinner(MmochatMap map, int line) {
		// String title = "冠军区服:";
		// String serverName = "";
		// String content = "";
		// for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
		// if (me.getCommonActivityScore() > 0) {
		// if (me.getCurChenHaoInfo() != null) {
		// serverName = me.getCurChenHaoInfo();
		// }
		// content += me.getName() + "(ID:"
		// + Integer.toHexString((me.getRoleId() % 10000000) * 3)
		// + ")\n";
		// }
		// }
		// title += serverName;

		String title = "最强区服";
		String content = "";
		List<MmochatServerTeamInfo> serverTeam = wuDaoPkGameWinTeamMap.get(map
				.getMapId());
		Collections.sort(serverTeam);
		int index = 0;
		for (MmochatServerTeamInfo team : serverTeam) {
			index++;
			if (index == 1) {
				content += MmochatUtil.wrapColor("\n[冠军:"
						+ team.getServerName() + "]\n", Color.yellow);
			} else if (index == 2) {
				content += MmochatUtil.wrapColor("\n[亚军:"
						+ team.getServerName() + "]\n", Color.yellow);
			} else if (index == 3) {
				content += MmochatUtil.wrapColor("\n[季军:"
						+ team.getServerName() + "]\n", Color.yellow);
			}
			content += team.getMembers();
		}

		int levelRange = (map.getMapId() - startMapId) * 10 + 30;

		// 将结果记录发给所有区服(不包含本服)
		MmochatEventType eventType;
		switch (levelRange) {
		case 30:
			eventType = MmochatEventType.跨服武道会30级组;
			break;
		case 40:
			eventType = MmochatEventType.跨服武道会40级组;
			break;
		case 50:
			eventType = MmochatEventType.跨服武道会50级组;
			break;
		case 60:
			eventType = MmochatEventType.跨服武道会60级组;
			break;
		case 70:
			eventType = MmochatEventType.跨服武道会70级组;
			break;
		case 80:
			eventType = MmochatEventType.跨服武道会80级组;
			break;
		case 90:
			eventType = MmochatEventType.跨服武道会90级组;
			break;
		case 100:
			eventType = MmochatEventType.跨服武道会100级组;
			break;
		case 110:
			eventType = MmochatEventType.跨服武道会110级组;
			break;
		case 120:
			eventType = MmochatEventType.跨服武道会120级组;
			break;
		default:
			eventType = MmochatEventType.跨服武道会120级组;
			break;
		}

		Mmochat_SendMultiServerWuDaoResult pack = new Mmochat_SendMultiServerWuDaoResult();
		pack.setEventType(eventType.getValue());
		pack.setTitle(title);
		pack.setContent(content);
		MmochatUtil.sendCommonPackToAllServer(pack);
	}

	// 发放奖励,剩下的玩家按积分最高的队长所在的区获胜
	// private static void dealAward(MmochatMap map) {
	// if (map == null) {
	// return;
	// }
	// synchronized (map) {
	// if (wuDaoPkGameAwardMap.get(map.getMapId()) == null) {
	// wuDaoPkGameAwardMap.put(map.getMapId(), true);
	// } else {
	// return;
	// }
	// }
	//
	// // 剩下的区组按积分排出前三名
	// List<serverScoreModel> servers = new ArrayList<serverScoreModel>();
	// // instId-->score
	// Map<Integer, Integer> serverScore = serverScores.get(map.getMapId());
	// if (serverScore.size() == 0) {
	// // 没有参赛区服
	// return;
	// }
	// for (Entry<Integer, Integer> entry : serverScore.entrySet()) {
	// int instId = entry.getKey();
	// int score = entry.getValue();
	// long dao = 0;
	// String serverName = null;
	// for (int line = 0; line < MmochatConstant.maxMapLineNum; line++) {
	// for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
	// if (me.getCommonActivityScore() > 0
	// && me.getRegServerInstId() == instId) {
	// dao += me.getDao();
	// serverName = me.getCurChenHaoInfo();
	// }
	// }
	// }
	// if (serverName == null) {
	// continue;
	// }
	// serverScoreModel ser = new serverScoreModel();
	// ser.setInstId(instId);
	// ser.setScore(score);
	// ser.setDao(dao);
	// ser.setServerName(serverName);
	// servers.add(ser);
	// }
	// Collections.sort(servers);
	//
	// // 奖励前3名
	// int[] honorAward = new int[] { 5000, 3000, 2000 };
	// int count = Math.min(3, servers.size());
	// String title = "前三名";
	// String memberNames = "";
	// String sysInfo = "";
	// for (int i = 0; i < count; i++) {
	// serverScoreModel ser = servers.get(i);
	// memberNames += MmochatUtil.wrapColor("[第" + (i + 1) + "名]"
	// + ser.getServerName(), Color.green)
	// + "\n";
	// sysInfo += "第" + (i + 1) + "名:" + ser.getServerName() + "、";
	// for (int line = 0; line < MmochatConstant.maxMapLineNum; line++) {
	// for (MmochatPlayer me : map.getLineRoleMap(line).values()) {
	// if (me.getCommonActivityScore() > 0
	// && me.getRegServerInstId() == ser.getInstId()) {
	// memberNames += me.getName()
	// + "(ID:"
	// + Integer
	// .toHexString((me.getRoleId() % 10000000) * 3)
	// + ")\n";
	// // 获得声望奖励
	// Mmochat_SendHonorChenHaoToOldServer pack = new
	// Mmochat_SendHonorChenHaoToOldServer(
	// me.getRegServerInstId());
	// pack.setRoleId(me.getRoleId() % 10000000);
	// pack.setAddHonor(honorAward[i]);
	// pack.setIndex(i);
	// MmochatUtil.sendMultiServerPack(pack);
	// }
	// }
	// }
	// memberNames += "\n";
	// }
	//
	// int levelRange = (map.getMapId() - startMapId) * 10 + 30;
	//
	// // 获胜消息发给所有区服及场内玩家
	// String msg = "本次" + levelRange + "级别段的跨服武道大会圆满结束,"
	// + MmochatUtil.wrapColor(sysInfo, Color.red) + ",恭喜以上区服!";
	// MmochatChatService.sendSystemMsg(msg);
	// MmochatChatService.sendSystemMsgToAllServer(msg);
	//
	// // 将结果记录发给所有区服(不包含本服)
	// MmochatEventType eventType;
	// switch (levelRange) {
	// case 30:
	// eventType = MmochatEventType.跨服武道会30级组;
	// break;
	// case 40:
	// eventType = MmochatEventType.跨服武道会40级组;
	// break;
	// case 50:
	// eventType = MmochatEventType.跨服武道会50级组;
	// break;
	// case 60:
	// eventType = MmochatEventType.跨服武道会60级组;
	// break;
	// case 70:
	// eventType = MmochatEventType.跨服武道会70级组;
	// break;
	// case 80:
	// eventType = MmochatEventType.跨服武道会80级组;
	// break;
	// case 90:
	// eventType = MmochatEventType.跨服武道会90级组;
	// break;
	// case 100:
	// eventType = MmochatEventType.跨服武道会100级组;
	// break;
	// case 110:
	// eventType = MmochatEventType.跨服武道会110级组;
	// break;
	// case 120:
	// eventType = MmochatEventType.跨服武道会120级组;
	// break;
	// default:
	// eventType = MmochatEventType.跨服武道会120级组;
	// break;
	// }
	//
	// Mmochat_SendMultiServerWuDaoResult pack = new
	// Mmochat_SendMultiServerWuDaoResult();
	// pack.setEventType(eventType.getValue());
	// pack.setTitle(title);
	// pack.setContent(memberNames);
	// MmochatUtil.sendCommonPackToAllServer(pack);
	// }

	static class serverScoreModel implements Comparable<serverScoreModel> {
		private int instId; // 实例号
		private int score; // 总积分
		private long dao; // 总道行
		private String serverName;

		public void setInstId(int instId) {
			this.instId = instId;
		}

		public void setScore(int score) {
			this.score = score;
		}

		public void setDao(long dao) {
			this.dao = dao;
		}

		public int getInstId() {
			return instId;
		}

		public int getScore() {
			return score;
		}

		public long getDao() {
			return dao;
		}

		public String getServerName() {
			return serverName;
		}

		public void setServerName(String serverName) {
			this.serverName = serverName;
		}

		@Override
		public int compareTo(serverScoreModel other) {
			if (score > other.getScore()) {
				return 0;
			} else if (score < other.getScore()) {
				return 1;
			} else {
				return (int) (other.getDao() - dao);
			}
		}
	}
}
